package com.tecklab.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tecklab.demo.aspect.OperateLog;
import com.tecklab.demo.common.BizException;
import com.tecklab.demo.common.PageData;
import com.tecklab.demo.common.Result;
import com.tecklab.demo.entity.UserEntity;
import com.tecklab.demo.mapper.UserMapper;
import com.tecklab.demo.service.UserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;


@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/api/users")
public class UserController {

    @Resource
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @SneakyThrows

    @GetMapping
    @OperateLog(optName = "用户-分页查询", optType = "查询")
    public Result getPage(@RequestParam("page") Integer pageNum, @RequestParam Integer size,
                          @RequestParam(required = false) String username,
                          @RequestParam(required = false) Integer accountType,
                          @RequestParam(required = false) Integer status) {
        log.info("分页查询用户列表");
        Page<UserEntity> page = new Page<>(pageNum, size);
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username);
        }
        if (accountType != null) {
            queryWrapper.eq("account_type", accountType);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        page = userMapper.selectPage(page, queryWrapper);
        return Result.success(new PageData<>(page.getRecords(), page.getTotal()));
    }

    //用户登录
    @GetMapping("/login")
    @OperateLog(optName = "用户登录", optType = "登录")
    public Result login(String username, String password) {
        //调佣Mapper方法
        return Result.success(userMapper.findByUsernameAndPassword(username, password));
    }

    // 根据ID获取用户
    @GetMapping("/{id}")
    @OperateLog(optName = "获取用户信息", optType = "查询")
    public Result getUserById(@PathVariable Integer id) {
        log.info("获取用户信息，ID: {}", id);
        return Result.success(userMapper.selectById(id));
    }

    // 添加用户
    @PostMapping
    @OperateLog(optName = "添加用户", optType = "新增")
    public Result addUser(@RequestBody UserEntity user) {
        user.setCreateTime(new Date());
        log.info("添加用户: {}", JSON.toJSONString(user));
        userMapper.insert(user);
        return Result.success();
    }

    @PutMapping("/{id}")
    @OperateLog(optName = "更新用户", optType = "修改")
    public Result updateUser(@PathVariable Integer id, @RequestBody UserEntity user) {
        user.setId(id);
        log.info("更新用户: {}", JSON.toJSONString(user));
        userMapper.updateById(user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @OperateLog(optName = "删除用户", optType = "删除")
    public Result deleteUser(@PathVariable Integer id) {
        if (userService.isAdmin(id)) {
            throw new BizException("不能删除管理员！");
        }
        log.info("删除用户，ID: {}", id);
        userMapper.deleteById(id);
        return Result.success();
    }

    @PostMapping("/batch/delete")
    @OperateLog(optName = "批量删除用户", optType = "删除")
    public Result<String> batchDeleteUser(@RequestBody List<Integer> idList) {
        log.info("删除用户，idList: {}", idList);
        return userService.batchDeleteUser(idList);
    }

    @PostMapping("/batch/resetpwd")
    @OperateLog(optName = "批量重置密码", optType = "修改")
    public Result<String> batchRestPwd(@RequestBody List<Integer> idList) {
        log.info("批量重置密码，idList: {}", idList);
        return userService.batchResetPwd(idList);
    }

    @PostMapping("/batch/create")
    @OperateLog(optName = "批量新增用户", optType = "新增")
    public Result batchCreateUser(@RequestBody JSONObject jsonObject) {
        userService.batchCreateUser((Integer) jsonObject.get("size"));
        return Result.success();
    }


    private WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();

    @GetMapping(value = "/webclient")
    @ResponseBody
    public Mono<String> webclient(HttpServletResponse response) {
        return webClient
                .get().uri("/hello?name=" + new Date())
                .exchange()
                .flatMap(clientResponse -> clientResponse.bodyToMono(String.class));
    }
}